package cn.etcweb.bait.baitframe.base.service.impl;

import cn.etcweb.bait.baitframe.base.mapper.MyMapper;
import cn.etcweb.bait.baitframe.base.service.BaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.List;

/**
 * 业务管理组件的基础功能实现类,此基类实现了基础的CRUD操作，具体业务中继承下来可直接使用。
 * @param <T>
 * @param <D>
 */
@Transactional
public class BaseServiceImpl<T,D extends MyMapper<T>> implements BaseService<T,D> {
    public transient final Logger log= LoggerFactory.getLogger(getClass());
    private Class<T> entityClass;

    private D baseMapper;

    @Override
    @Transactional(readOnly = true)
    public T get(Serializable id) throws Exception {
        return baseMapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional(readOnly = true)
    public List<T> queryAll() throws Exception {
        return baseMapper.selectAll();
    }

    @Override
    @Transactional(readOnly = false)
    public void save(T entity) throws Exception {
        baseMapper.insert(entity);
    }

    @Override
    public void deleteBusiness(Serializable id) throws Exception {
        baseMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deleteBusiness(String[] ids) throws Exception {
        for (String id : ids) {
            baseMapper.deleteByPrimaryKey(id);
        }
    }

    /*@Override
    public void afterPropertiesSet() throws Exception {
// 根据T,反射获得entityClass
        entityClass = GenericsUtils.getSuperClassGenricType(getClass(), 0);
        // 根据M,反射获得符合M类型的manager
        List<Field> fields = BeanUtils.getFieldsByType(this, GenericsUtils.getSuperClassGenricType(getClass(), 1));
        Assert.isTrue(fields.size() == 1, "subclass's has not only one entity manager property.");
        try {
            entityDaoInf = (D) BeanUtils.forceGetProperty(this, fields.get(0).getName());
            Assert.notNull(entityDaoInf, "subclass not inject manager to action sucessful.");
        } catch (Exception e) {
            ReflectionUtils.handleReflectionException(e);
        }
    }*/
}
